<script setup lang="ts">
import type { AppointmentManagement } from '@shared/types/appointment'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed, nextTick, ref } from 'vue'

interface Props {
  modelValue: boolean
  batchId: string
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success', appointments?: AppointmentManagement[]): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 数据状态
const loading = ref(false)
const adding = ref(false)
const appointments = ref<AppointmentManagement[]>([])
const selectedAppointments = ref<AppointmentManagement[]>([])

// 搜索和过滤
const searchText = ref('')
const statusFilter = ref<string>('')
const placeholderFilter = ref<boolean | null>(null)
const priorityFilter = ref<number[]>([])

// 表格引用
const tableRef = ref()

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: value => emit('update:modelValue', value),
})

const filteredAppointments = computed(() => {
  let filtered = appointments.value

  // 搜索过滤
  if (searchText.value) {
    const search = searchText.value.toLowerCase()
    filtered = filtered.filter(item =>
      item.full_name.toLowerCase().includes(search)
      || item.passport_number.toLowerCase().includes(search)
      || item.email.toLowerCase().includes(search),
    )
  }

  // 状态过滤
  if (statusFilter.value) {
    filtered = filtered.filter(item => item.appointment_status === statusFilter.value)
  }

  // 类型过滤
  if (placeholderFilter.value !== null) {
    filtered = filtered.filter(item => item.is_placeholder === placeholderFilter.value)
  }

  // 优先级过滤
  if (priorityFilter.value && priorityFilter.value.length > 0) {
    filtered = filtered.filter(item => priorityFilter.value.includes(item.priority))
  }

  return filtered
})

// 加载预约记录（未分配到任何批次的）
async function loadAppointments() {
  loading.value = true
  try {
    const response = await window.api.appointment.list(
      {
        batch_id: null, // 只查询未分配到批次的记录
        appointment_status: ['pending', 'failed'], // 只查询可以重新预约的记录
        // 排除监控数据，避免被用于批量或手动选择
        is_monitor: false,
      },
      { page: 1, page_size: 1000 },
    )

    if (response.success) {
      appointments.value = response.data.appointments
    }
    else {
      ElMessage.error(response.error || '加载预约记录失败')
    }
  }
  catch (error) {
    console.error('加载预约记录失败:', error)
    ElMessage.error('加载预约记录失败')
  }
  finally {
    loading.value = false
  }
}

// 搜索处理
function handleSearch() {
  // 搜索会通过计算属性自动触发
}

// 选择变化
function handleSelectionChange(selection: AppointmentManagement[]) {
  selectedAppointments.value = selection
}

// 全选
function selectAll() {
  tableRef.value?.toggleAllSelection()
}

// 清空选择
function clearSelection() {
  tableRef.value?.clearSelection()
}

// 添加到批次
async function addTooBatch() {
  if (!props.batchId || selectedAppointments.value.length === 0)
    return

  adding.value = true
  try {
    const appointmentIds = selectedAppointments.value.map(item => item.id)
    // @ts-expect-error batch API 可能未在类型定义中，但实际存在
    const response = await window.api.batch.addAppointments(props.batchId, appointmentIds)

    if (response.success) {
      ElMessage.success(`成功添加 ${appointmentIds.length} 个预约记录到批次`)
      emit('success')
      visible.value = false
      selectedAppointments.value = []
    }
    else {
      ElMessage.error(response.error || '添加到批次失败')
    }
  }
  catch (error) {
    console.error('添加到批次失败:', error)
    ElMessage.error('添加到批次失败')
  }
  finally {
    adding.value = false
  }
}

// 确认选择（非批次模式）
function confirmSelect() {
  const plain: AppointmentManagement[] = selectedAppointments.value.map(item => ({ ...item } as AppointmentManagement))
  emit('success', plain)
  visible.value = false
}

// 快速选择：根据过滤结果选择前 N 条
const quickSelectCount = ref(30)
async function selectTopN(count?: number) {
  const n = Math.max(1, Number((count ?? quickSelectCount.value) || 0))
  const data = filteredAppointments.value
  if (!Array.isArray(data) || data.length === 0)
    return
  const take = Math.min(n, data.length)
  tableRef.value?.clearSelection()
  // 等待清空选择生效后再批量选中，避免闪烁与状态错乱
  await nextTick()
  for (let i = 0; i < take; i++)
    tableRef.value?.toggleRowSelection(data[i], true)
}

// 工具函数
function getPriorityType(priority: number): any {
  // 返回 undefined 表示不设置 type，避免传入非法空字符串
  const types: Record<number, string | undefined> = { 1: 'danger', 2: 'warning', 3: undefined, 4: 'info', 5: 'success' }
  return types[priority]
}

function getStatusType(status: string): any {
  const types: Record<string, string> = {
    pending: 'warning',
    booked: 'success',
    confirmed: 'success',
    cancelled: 'info',
    failed: 'danger',
  }
  return types[status]
}

function getStatusText(status: string): string {
  const texts: Record<string, string> = {
    pending: '待处理',
    booked: '已预约',
    confirmed: '已确认',
    cancelled: '已取消',
    failed: '失败',
  }
  return texts[status] || status
}

function formatDateTime(dateStr: string | Date | null | undefined): string {
  if (!dateStr)
    return ''
  const date = typeof dateStr === 'string' ? new Date(dateStr) : dateStr
  return date.toLocaleDateString('zh-CN')
}
</script>

<template>
  <el-dialog
    v-model="visible"
    title="选择预约记录"
    width="900px"
    @open="loadAppointments"
  >
    <div class="selection-header">
      <el-input
        v-model="searchText"
        placeholder="搜索姓名、护照号、邮箱..."
        clearable
        style="width: 300px"
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <div class="filter-controls">
        <el-select v-model="statusFilter" placeholder="状态" clearable style="width: 120px">
          <el-option label="待处理" value="pending" />
          <el-option label="失败" value="failed" />
        </el-select>

        <el-select v-model="placeholderFilter" placeholder="类型" clearable style="width: 120px">
          <el-option label="真实数据" :value="false" />
          <el-option label="占号数据" :value="true" />
        </el-select>

        <el-select v-model="priorityFilter" multiple collapse-tags collapse-tags-tooltip placeholder="优先级" clearable style="width: 140px">
          <el-option label="1级" :value="1" />
          <el-option label="2级" :value="2" />
          <el-option label="3级" :value="3" />
          <el-option label="4级" :value="4" />
          <el-option label="5级" :value="5" />
        </el-select>
      </div>
    </div>

    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="filteredAppointments"
      stripe
      border
      height="400"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />

      <el-table-column prop="sequence_number" label="序号" width="120">
        <template #default="{ row }">
          <el-tag v-if="row.is_placeholder" type="warning" size="small">
            占号
          </el-tag>
          {{ row.sequence_number }}
        </template>
      </el-table-column>

      <el-table-column prop="full_name" label="姓名" width="100" />

      <el-table-column prop="passport_number" label="护照号码" width="120" />

      <el-table-column prop="email" label="邮箱" width="200" show-overflow-tooltip />

      <el-table-column prop="priority" label="优先级" width="80" align="center">
        <template #default="{ row }">
          <el-tag :type="getPriorityType(row.priority)" size="small">
            {{ row.priority }}级
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="appointment_status" label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.appointment_status)" size="small">
            {{ getStatusText(row.appointment_status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="created_at" label="创建时间" width="150">
        <template #default="{ row }">
          {{ formatDateTime(row.created_at) }}
        </template>
      </el-table-column>
    </el-table>

    <div class="selection-info">
      <span>已选择 {{ selectedAppointments.length }} / {{ filteredAppointments.length }} 个预约记录</span>
      <div class="selection-actions">
        <div class="quick-select">
          <span>快速选择</span>
          <el-input-number v-model="quickSelectCount" :min="1" :max="filteredAppointments.length || 1" size="small" />
          <el-button size="small" type="primary" @click="selectTopN()">
            前 N 个
          </el-button>
        </div>
        <el-button @click="selectAll">
          全选
        </el-button>
        <el-button @click="clearSelection">
          清空
        </el-button>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">
          取消
        </el-button>
        <el-button
          v-if="batchId"
          type="primary"
          :disabled="selectedAppointments.length === 0"
          :loading="adding"
          @click="addTooBatch"
        >
          添加到批次 ({{ selectedAppointments.length }})
        </el-button>
        <el-button
          v-else
          type="primary"
          :disabled="selectedAppointments.length === 0"
          @click="confirmSelect"
        >
          确认选择 ({{ selectedAppointments.length }})
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.selection-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.filter-controls {
  display: flex;
  gap: 8px;
}

.selection-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
}

.selection-actions {
  display: flex;
  gap: 8px;
}

.dialog-footer {
  text-align: right;
}

.quick-select {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  margin-right: 8px;
}
</style>
